package com.taotao.rest.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.taotao.common.util.JsonUtils;
import com.taotao.mapper.TbItemCatMapper;
import com.taotao.pojo.TbItemCat;
import com.taotao.pojo.TbItemCatExample;
import com.taotao.pojo.TbItemCatExample.Criteria;
import com.taotao.rest.dao.JedisClient;
import com.taotao.rest.pojo.ItemCatNode;
import com.taotao.rest.pojo.ItemCatResult;
import com.taotao.rest.service.ItemCatService;

@Service("itemCatService")
public class ItemCatServiceImpl implements ItemCatService {
	@Autowired
	private TbItemCatMapper itemCatMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${INDEX_ITEM_CAT_REDIS_KEY}")
	private String INDEX_ITEM_CAT_REDIS_KEY;

	@Override
	public ItemCatResult getItemCatList() {
		try {
			String result = jedisClient.hget(INDEX_ITEM_CAT_REDIS_KEY, 0 + "");
			if (!StringUtils.isBlank(result)) {
				List<ItemCatNode> list = JsonUtils.toList(result, ItemCatNode.class);
				ItemCatResult result0 = new ItemCatResult();
				result0.setData(list);
				return result0;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List list = getItemCatList(0);
		try {
			String json = JsonUtils.toJson(list);
			jedisClient.hset(INDEX_ITEM_CAT_REDIS_KEY, 0 + "", json);
		} catch (Exception e) {
			// TODO: handle exception
		}

		ItemCatResult result = new ItemCatResult();
		result.setData(list);
		return result;
	}

	private List getItemCatList(long parentId) {
		if (parentId == 0) {
			PageHelper.startPage(1, 14);
		}
		TbItemCatExample example = new TbItemCatExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbItemCat> list = itemCatMapper.selectByExample(example);
		List resultList = new ArrayList<>();
		for (TbItemCat itemCat : list) {
			if (itemCat.getIsParent()) {

				ItemCatNode node = new ItemCatNode();
				node.setUrl("/products/" + itemCat.getId() + ".html");
				if (parentId == 0) {
					node.setName("<a href='/products/" + itemCat.getId() + ".html'>" + itemCat.getName() + "</a>");
				} else {
					node.setName(itemCat.getName());
				}
				node.setItem(getItemCatList(itemCat.getId()));
				resultList.add(node);
			} else {
				resultList.add("/products/" + itemCat.getId() + ".html|" + itemCat.getName());
			}
		}

		return resultList;
	}

}
